package com.zuipin.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zuipin.entity.BaseDictionaryData;
import com.zuipin.entity.product.ProductExtInfo;
import com.zuipin.entity.product.TagInfo;
import com.zuipin.framework.annotation.Inject;
import com.zuipin.framework.annotation.Json;
import com.zuipin.framework.annotation.Jsons;
import com.zuipin.framework.annotation.Valid;
import com.zuipin.framework.annotation.Valids;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.service.IProductExtInfoService;
import com.zuipin.service.IProductInfoService;
import com.zuipin.service.ITagInfoService;
import com.zuipin.service.ITagProductService;
import com.zuipin.util.Pagination;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.ProVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 商品标签信息Controller
 *
 * @ClassName TagInfoController
 * @author wangcongyi
 * @date 2017年5月9日 上午9:50:11
 */

@Controller
@RequestMapping(value = "/tagInfo")
@Api(value = "商品标签信息", description = "商品标签信息-wangcongyi")
public class TagInfoController {
	
	@Resource
	private IProductExtInfoService	productExtInfoService;
	@Resource
	private IProductInfoService		productInfoService;
	@Resource
	private ITagInfoService			tagInfoService;
	@Resource
	private ITagProductService		tagProductService;
	
	@ResponseBody
	@RequestMapping(value = "/getCurrentNo", method = RequestMethod.GET)
	@ApiOperation(value = "三期-获取当前商品标签编号-wangcongyi", notes = "获取当前商品标签编号" + "</br>返回码" + "</br>0-成功" + "</br>1004-系统异常")
	public Result<Map<String, Object>> getCurrentNo() {
		Result<Map<String, Object>> result = new Result<>();
		Map<String, Object> map = new HashMap<>();
		String maxNo = tagInfoService.getMaxNo();
		if (null != maxNo) {
			int CurrentNo = Integer.parseInt(maxNo);
			map.put("NO", "BQ" + StringUtil.fillStr(String.valueOf(++CurrentNo), 5, false, "0"));
		} else {
			map.put("NO", "BQ00001");
		}
		result.setData(map);
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@Jsons({ @Json(type = TagInfo.class, include = "id,name,tagNo,pcImgUrl,wapImgUrl,state,sysId,createTime") })
	@RequestMapping(value = "/seachTagInfo", method = RequestMethod.POST)
	@ApiOperation(value = "三期-分页显示标签信息列表-wangcongyi", notes = "分页显示标签信息列表" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常")
	@Valids({ @Valid(name = "tagInfo.name", maxLength = 100), @Valid(name = "tagInfo.state"), @Valid(name = "tagInfo.proSkus"), @Valid(name = "tagInfo.sysId", required = true),
			@Valid(name = "page.pageNumber", required = true), @Valid(name = "page.pageSize", required = true), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.name", value = "商品标签名称", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.state", value = "商品标签状态 0:未启用 1:启用 2:禁用", dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.tagNo", value = "商品标签编号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "page.pageNumber", value = "页码", required = true, dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "page.pageSize", value = "单页记录数", required = true, dataType = "integer", paramType = "query"), })
	public Result<List<TagInfo>> seachTagInfo(@Inject @ApiIgnore TagInfo tagInfo, @Inject @ApiIgnore Pagination page) {
		PageResult<List<TagInfo>> result = new PageResult<>();
		
		result.setData(tagInfoService.seachTagInfo(tagInfo, page));
		result.setTotal_record(page.getTotalRecord());
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@Jsons({ @Json(type = TagInfo.class, include = "id,name,tagNo,pcImgUrl,wapImgUrl,state,sysId,createTime") })
	@RequestMapping(value = "/findTagInfoById", method = RequestMethod.GET)
	@ApiOperation(value = "三期-通过ID查询标签信息-wangcongyi", notes = "通过ID查询标签信息" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常")
	@Valids({ @Valid(name = "tagInfo.id", required = true), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.id", value = "标签ID", dataType = "long", paramType = "query"), })
	public Result<TagInfo> findTagInfoById(@Inject @ApiIgnore TagInfo tagInfo) {
		Result<TagInfo> result = new Result<>();
		result.setData(tagInfoService.findTagInfoById(tagInfo));
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@Jsons({ @Json(type = ProductExtInfo.class, include = "id,proSku,title") })
	@RequestMapping(value = "/findProExtByTagId", method = RequestMethod.GET)
	@ApiOperation(value = "根据标签ID查询商品信息列表-wangcongyi", notes = "根据标签ID查询商品信息列表" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常")
	@Valids({ @Valid(name = "tagInfo.id", required = true), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.id", value = "标签ID", dataType = "long", paramType = "query"), })
	public Result<?> findProExtByTagId(@Inject @ApiIgnore BaseDictionaryData tagInfo) {
		Result<List<ProductExtInfo>> result = new Result<>();
		result.setData(productExtInfoService.findProExtByTagId(tagInfo));
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/removeTagInfo", method = RequestMethod.GET)
	@ApiOperation(value = "移除对应商品标签信息-wangcongyi", notes = "移除对应商品标签信息" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常")
	@Valids({ @Valid(name = "sysId", required = true), @Valid(name = "skus", required = true) })
	@ApiImplicitParams({ @ApiImplicitParam(name = "skus", value = "商品Sku集", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统ID", dataType = "long", paramType = "query") })
	public Result<?> findTagInfoById(@RequestParam(value = "skus") String skus, @RequestParam(value = "sysId") Long sysId) {
		Result<Boolean> result = new Result<>();
		List<String> list = Arrays.asList(skus.split(","));
		JSONObject params = new JSONObject();
		params.put("delFlag", true);
		params.put("sysId", sysId);
		
		// 删除重复标签的商品 禁用的标签不移除 在tag—product映射关系表中 delFlag置为1即可
		tagProductService.removeRepeat(params, list);
		
		// 然后删除产品表中保存的tagId信息 update tagId=null
		if (productExtInfoService.removeTagInfo(sysId, list) > 0) {
			
			result.setData(true);
		} else {
			result.setData(false);
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveTagInfo", method = RequestMethod.POST)
	@ApiOperation(value = "三期-添加商品标签信息-wangcongyi", notes = "添加商品标签信息" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常" + "<br/>3005-商品标签编号重复")
	@Valids({ @Valid(name = "tagInfo.name", maxLength = 40, required = true), @Valid(name = "tagInfo.pcImgUrl", required = true),
			@Valid(name = "tagInfo.pcImgKey", required = true), @Valid(name = "tagInfo.wapImgUrl", required = true), @Valid(name = "tagInfo.wapImgKey", required = true),
			@Valid(name = "tagInfo.tagNo", required = true), @Valid(name = "tagInfo.proSkus", required = true), @Valid(name = "tagInfo.sysId", required = true), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.name", value = "标签名称", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.tagNo", value = "标签编号", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.pcImgUrl", value = "PC标签图片", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.pcImgKey", value = "PC标签key", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.wapImgUrl", value = "WAP标签图片", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.wapImgKey", value = "WAP标签图片key", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.proSkus", value = "商品sku集", required = true, dataType = "string", paramType = "query"), })
	public Result<String> saveTagInfo(@Inject @ApiIgnore TagInfo tagInfo) {
		Result<String> result = new Result<>();
		TagInfo info = tagInfoService.isRepeat(tagInfo);
		if (null != info) {
			result.setErrorCode(ErrorCode.OBJECT_EXIST);
			result.setMessage("商品标签编号重复");
		} else {
			tagInfo.setId(null);
			tagInfoService.insertTagInfo(tagInfo);
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setMessage("商品标签添加成功");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateTagInfo", method = RequestMethod.POST)
	@ApiOperation(value = "三期-修改商品标签信息-wangcongyi", notes = "修改商品标签信息" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常" + "<br/>2000-商品标签信息未找到"
			+ "<br/>3005-商品标签编号重复")
	@Valids({ @Valid(name = "tagInfo.id", required = true), @Valid(name = "tagInfo.tagNo"), @Valid(name = "tagInfo.name", maxLength = 40), @Valid(name = "tagInfo.pcImgUrl"),
			@Valid(name = "tagInfo.pcImgKey"), @Valid(name = "tagInfo.wapImgUrl"), @Valid(name = "tagInfo.wapImgKey"), @Valid(name = "tagInfo.proSkus"), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.id", value = "标签ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.tagNo", value = "标签编号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.name", value = "标签名称", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.pcImgUrl", value = "PC标签图片", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.pcImgKey", value = "PC标签图片KEY", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.wapImgUrl", value = "WAP标签图片", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.wapImgKey", value = "WAP标签图片KEY", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.proSkus", value = "商品sku集", dataType = "string", paramType = "query"), })
	public Result<Map<String, Object>> updateTagInfo(@Inject @ApiIgnore TagInfo tagInfo) throws CustomException {
		Result<Map<String, Object>> result = new Result<>();
		TagInfo info = tagInfoService.isRepeat(tagInfo);
		if (null != info) {
			if (!tagInfo.getId().equals(info.getId())) {
				result.setErrorCode(ErrorCode.OBJECT_EXIST);
				result.setMessage("商品标签编号重复");
				return result;
			}
		}
		TagInfo oldInfo = tagInfoService.findTagInfoById(tagInfo);
		Map<String, Object> map = new HashMap<>();
		if (null != tagInfo.getPcImgUrl()) {
			if (null == tagInfo.getPcImgKey()) {
				result.setErrorCode(ErrorCode.ELSE);
				result.setMessage("PC端图片KEY值为空");
				return result;
			}
			map.put("pcImgKey", oldInfo.getPcImgKey());
		}
		if (null != tagInfo.getWapImgUrl()) {
			if (null == tagInfo.getWapImgKey()) {
				result.setErrorCode(ErrorCode.ELSE);
				result.setMessage("WAP端图片KEY值为空");
				return result;
			}
			map.put("wapImgKey", oldInfo.getWapImgKey());
		}
		tagInfo.setState(null);
		tagInfoService.updateTagInfo(tagInfo);
		result.setData(map);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setMessage("商品标签修改成功");
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/isSettledTagInfo", method = RequestMethod.POST)
	@ApiOperation(value = "三期-判断是否已设置标签-wangcongyi", notes = "判断是否已设置标签" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常"
			+ "</br>3005-已存在启用标签")
	@Valids({ @Valid(name = "proSkus", required = true), @Valid(name = "tagId"), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "proSkus", value = "商品SKU集", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "tagId", value = "商品标签ID(修改时需要传值)", dataType = "long", paramType = "query"), })
	public Result<?> isSettledTagInfo(@RequestParam String proSkus, @RequestParam(required = false) Long tagId) {
		Result<String> result = new Result<>();
		String[] arr = proSkus.split(",");
		List<String> proSkuList = new ArrayList<>();
		if (null != arr) {
			for (String proSku : arr) {
				proSkuList.add(proSku);
			}
		}
		List<ProductExtInfo> proExts = productExtInfoService.isSettledTagInfo(proSkuList, tagId);
		StringBuilder sb = new StringBuilder();
		String data = "";
		if (proExts != null && !proExts.isEmpty()) {
			sb.append("商品[");
			String sp = "";
			for (ProductExtInfo productExtInfo : proExts) {
				sb.append(sp);
				sb.append(productExtInfo.getProSku());
				sp = ",";
			}
			data = sb.toString().substring(3);
			sb.append("]已存在启用标签！是否覆盖?");
			result.setErrorCode(ErrorCode.OBJECT_EXIST);
			result.setMessage(sb.toString());
			result.setData(data);
			return result;
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/findSkusByTagId", method = RequestMethod.GET)
	@ApiOperation(value = "三期-通过标签ID获取SKU集-wangcongyi", notes = "通过标签ID获取SKU集" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常")
	@Valids({ @Valid(name = "tagInfo.id", required = true), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.id", value = "标签编号", required = true, dataType = "long", paramType = "query"), })
	public Result<String> findSkusByTagId(@Inject @ApiIgnore TagInfo tagInfo) {
		Result<String> result = new Result<>();
		result.setData(tagInfoService.findSkusByTagId(tagInfo));
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/modifyState", method = RequestMethod.GET)
	@ApiOperation(value = "三期-修改商品标签状态-wangcongyi", notes = "修改商品标签状态" + "</br>返回码" + "</br>0-成功" + "</br>1000-状态值输入错误" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常"
			+ "</br>5002-请正确传输状态值")
	@Valids({ @Valid(name = "tagInfo.id", required = true), @Valid(name = "tagInfo.state", required = true), @Valid(name = "tagInfo.sysId", required = true) })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.id", value = "标签编号", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.state", value = "是否冻结  0:未启用 1:启用 2:禁用", required = true, dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.sysId", value = "系统ID", required = true, dataType = "long", paramType = "query") })
	public Result<?> modifyState(@Inject @ApiIgnore TagInfo tagInfo, @RequestParam("flag") Boolean flag) throws CustomException {
		Result<?> result = new Result<>();
		// StringBuilder stateStr = new StringBuilder();
		// if (TagInfo.ENABLED.equals(tagInfo.getState())) {
		// stateStr.append("启用");
		// } else if (TagInfo.DISABLED.equals(tagInfo.getState())) {
		// stateStr.append("禁用");
		// } else {
		// result.setErrorCode(ErrorCode.STATE_INVALID);
		// result.setMessage("请正确传输状态值！");
		// return result;
		// }
		
		result = tagInfoService.modifyState(tagInfo, flag);
		
		return result;
		
		/*//获取标签下的所有商品
		List<String> proSkuList = tagProductService.selectSkusByTagId(tagInfo.getId());
		// 批量更新productExtInfo表里面的tagID
		productExtInfoService.updateTagInfoBatch(tagInfo, proSkuList);*/
		/*		
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setMessage("标签" + stateStr + "成功！");
				return result;*/
	}
	
	@Jsons({ @Json(type = TagInfo.class, include = "id,name,tagNo,pcImgUrl,wapImgUrl,state,sysId,createTime,updateTime,products") })
	@RequestMapping(value = "/getTagInfoDetail", method = RequestMethod.GET)
	@ApiOperation(value = "三期-获取标签信息详情-wangcongyi", notes = "获取标签信息详情" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数错误" + "</br>1002-必填项未填写" + "</br>1004-系统异常"
			+ "</br>2000-商品标签信息未找到")
	@Valids({ @Valid(name = "tagInfo.id", required = true), @Valid(name = "tagInfo.sysId", required = true), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "tagInfo.id", value = "商品标签ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "tagInfo.sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"), })
	public Result<TagInfo> getTagInfoDetail(@Inject @ApiIgnore TagInfo tagInfo) {
		Result<TagInfo> result = new Result<>();
		JSONObject params = new JSONObject();
		// 获取商品商标实体
		TagInfo info = tagInfoService.findTagInfoById(tagInfo);
		if (null != info) {
			// 获取商品标签下的商品SKU集
			List<String> skus = tagProductService.selectSkusByTagId(tagInfo.getId());
			List<ProVo> proVos = null;
			if (null != skus && !skus.isEmpty()) {
				StringBuilder proSkuBuilder = new StringBuilder();
				String sp = "";
				for (int i = 0; i < skus.size(); i++) {
					proSkuBuilder.append(sp);
					proSkuBuilder.append("'");
					proSkuBuilder.append(skus.get(i));
					proSkuBuilder.append("'");
					sp = ",";
				}
				params.put("sysId", tagInfo.getSysId());
				params.put("proSkus", proSkuBuilder.toString());
				Pagination page = new Pagination();
				page.setPageNumber(1);
				page.setPageSize(skus.size());
				proVos = productInfoService.findPro(params, page);
			}
			info.setProducts(proVos);
			result.setData(info);
			result.setErrorCode(ErrorCode.SUCCESS);
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("请输入正确的商品标签信息");
		}
		return result;
	}
	
}
